package com.gitee.feizns.zxw.commons.intercepeters;

import com.gitee.feizns.web.ex.UnauthorizedException;
import com.gitee.feizns.web.utils.UserUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author feizns
 * @since 2019/9/9
 */
public class TokenValidateInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ( handler instanceof HandlerMethod) {
            TokenValidate validate = getAnnotation((HandlerMethod) handler);
            if ( validate != null && UserUtils.getNullableId() == null )
                throw new UnauthorizedException();
        }
        return true;
    }

    private TokenValidate getAnnotation(HandlerMethod method) {
        TokenValidate validate = method.getMethodAnnotation(TokenValidate.class);
        if ( validate == null )
            return method.getBeanType().getAnnotation(TokenValidate.class);
        return validate;
    }

}
